﻿using fuzhu;
using LH.Model.PU;
using Npgsql.Logging;
using SqlSuarEntity;
using SqlSugar;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Runtime.ConstrainedExecution;
using XXX.Bo;
using XXX.Common;
using XXX.Models;
using XXX.Models.WMS;
using XXX.Models.XXXEntities;
using Yonyou.U8.BO;
using ZDEntity;
using static XXX.Models.WDFT.WDFT_SaleOrderJinDu;
using static XXX.Models.WMS.ScanBarcode;

namespace XXX.Bo
{
    public class WMS_BARCODEVM : WMS_BARCODE
    {
        //当前的数据库连接字符串
        public string conStr { get; set; }
        public string cacc { get; set; }
        public string xmlConfig { get; set; }
        public static string cDatabase = "";
        /// <summary>
        /// 威德封头用： 剩余数量是否作废 1: 作废，0：继续使用 作废把 状态变更为“已出库”
        /// </summary>
        public int bLeaveInvalid { get; set; }
        public string cInvCodeHB { get; set; }  //合并后的存货编码
        public string cInvName { get; set; }
        public string cInvStd { get; set; }
        public string cInvAddCode { get; set; }

        //是否序列号管理,和是否出库检查状态一起使用。如果出库检查状态，默认全部勾选。 如果出库不检查，这个勾了，只这个存货管理
        public bool bSerial { get; set; }
        //是否托码： 托码单独的表
        public bool bTray { get; set; }
        public string cDefWareHouse { get; set; }  //存货档案默认仓库
        public string cDefPosCode { get; set; }  //存货档案默认货位
        //public string cType { get; set; }  //打印类型
        public WMS_BARCODEVM()
        {
            //conStr
            conStr = CanShu.conStr;
            cacc = CanShu.cZT;
            //初始化定义xmlconfig
            xmlConfig = XmlOperation.GetConfigXML();
        }

        //清理敏感信息
        public void clearConstr()
        {
            //conStr
            conStr = null;
            //初始化定义xmlconfig
            xmlConfig = null;
        }

        /// <summary>
        /// 读取条码中的存货编码，返回的是List，如果是箱托多批次的，返回的是list
        /// </summary>
        /// <param name="corg">组织</param>
        /// <param name="cbarcode">条码</param>
        /// <param name="cbarcode">出库类型</param>
        /// <returns></returns>
        public RetModel2 AA_GetBarcode(string cbarcode, string clx, string cwhcode)
        {
            try
            {
                if (string.IsNullOrEmpty(cbarcode))
                {
                    throw new Exception("没有扫码！");
                }
                //存货过程更改成代码

                //1： 入库  2：出库 0：不检验
                string cFangxiang = "0";

                if (clx.Contains("入库") && clx != "入库装托")
                {
                    cFangxiang = "1";
                }
                else if (clx.Contains("出库"))
                {
                    cFangxiang = "2";
                }
                else
                {
                    cFangxiang = "0";
                }

                
                    //箱条码
                    using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                    {
                        ConnectionString = conStr,
                        DbType = SqlSugar.DbType.SqlServer,
                        IsAutoCloseConnection = true
                    }))
                    {
                    List<WMS_BARCODEVM> bARCODEVM = new List<WMS_BARCODEVM>();
                    //T开头的托码单,没有考虑自由项
                    if (cbarcode.Substring(0, 1) == "T")
                    {
                        bARCODEVM = db.Queryable<ZDY_WMS_V_TrayInfo>()
                            .InnerJoin<Inventory>((a, i) => a.cInvCode == i.cInvCode)
                            .Where((a, i) => a.cTrayNo == cbarcode)
                            .Select((a, i) => new WMS_BARCODEVM
                            {
                                Barcodeno = a.cTrayNo,
                                cInvCode = a.cInvCode,
                                cInvName = i.cInvName,
                                cInvStd = i.cInvStd,
                                cInvAddCode = i.cInvAddCode,
                                cBatch = a.cBatch,
                                iQty = a.iQty,
                                iOriQty = a.iQty,
                                cWhCode = a.cWhCode,
                                cPosCode = a.cPosCode,
                                BarLevel = 0,
                                iSourceID =0, 
                                cState = a.cState,
                                cInvCodeHB = string.IsNullOrWhiteSpace(a.cBatch) ? "a.cInvCode+" : a.cInvCode + "|" + a.cBatch,
                                cDefPosCode = i.cPosition,
                                cDefWareHouse = i.cDefWareHouse,
                                dMDate = a.dMDate,
                                dVDate = a.dVDate,
                                cFree1 = a.cFree1,
                                cFree2 = a.cFree2,
                                cFree3 = a.cFree3,
                                cFree4 = a.cFree4, 
                                bSerial = i.bSerial
                            }
                            ).ToList();
                    }
                    else
                    {
                        bARCODEVM = db.Queryable<WMS_BARCODE>()
                            .InnerJoin<Inventory>((a, i) => a.cInvCode == i.cInvCode)
                            .Where((a, i) => a.Barcodeno == cbarcode)
                            .Select((a, i) => new WMS_BARCODEVM
                            {
                                Barcodeno = a.Barcodeno,
                                cInvCode = a.cInvCode,
                                cInvName = i.cInvName,
                                cInvStd = i.cInvStd,
                                cInvAddCode = i.cInvAddCode,
                                cBatch = a.cBatch,
                                iQty = a.iQty,
                                iOriQty = a.iOriQty,
                                cWhCode = a.cWhCode,
                                cPosCode = a.cPosCode,
                                BarLevel = a.BarLevel,
                                iSourceID = a.iSourceID,
                                RKDate = a.RKDate,
                                cInCode = a.cInCode,
                                cInType = a.cInType,
                                cState = a.cState,
                                cInvCodeHB = string.IsNullOrWhiteSpace(a.cBatch) ? "a.cInvCode+" : a.cInvCode + "|" + a.cBatch,
                                cDefPosCode = i.cPosition,
                                cDefWareHouse = i.cDefWareHouse,
                                dMDate = a.dMDate,
                                dVDate = a.dVDate,
                                cFree1 = a.cFree1,
                                cFree2 = a.cFree2,
                                cFree3 = a.cFree3,
                                cFree4 = a.cFree4,
                                cBDefine1 = a.cBDefine1,
                                cBDefine2 = a.cBDefine2,
                                cBDefine3 = a.cBDefine3,
                                cBDefine4 = a.cBDefine4,
                                bSerial = i.bSerial
                            }
                            ).ToList();
                    }
                          

                        if ( bARCODEVM == null || bARCODEVM.Count == 0)
                        {
                            //成品入库和入库装托的，都根据规则先生成条码
                            if (cbarcode.Substring(0, 1) != "T" && (clx == "成品入库" || clx == "入库装托"))
                            {
                                //根据条码规则插入到系统里
                                //  规则删除	二维码内容：产品编码 || 生产工单 || 批次号码 || 流水号 || 包装数量 。
                                //举例：1066010193 || 0000000325 - 1 || 202412010005 || 12 || 100
                                // 新规则： 产品编码 || 生产工单 || 工单批次 || 批次号码 || 流水号 || 包装数量
                                //	举例：1066010193 || 0000000325 - 1 || H2025 - 05 - 1 || BN2505200027 || 12 || 100
                                //	生产工单：取的是SDC的生产工单
                                //	工单批次：取的是生产工单的批次
                                RetModel2 ret = AddBarcode(cbarcode, db);
                                if (ret.code != 200)
                                {
                                    return ret;
                                }
                                else
                                {
                                    bARCODEVM.Add((WMS_BARCODEVM)ret.data);
                                }
                            }
                            else
                            {
                                return new RetModel2() { code = 0, message = "条码不存在", data = null };
                            }

                        }
                        //严格控制，或者勾选了U8的序列号管理
                        if (WMSPara.StatusControl == "Y" || bARCODEVM[0].bSerial)
                        {


                            //空条码设置成未入库
                            if (bARCODEVM[0].cState == null || bARCODEVM[0].cState == "")
                            {
                                bARCODEVM[0].cState = "未入库";
                            }
                            if ((bARCODEVM[0].cState != "未入库" && bARCODEVM[0].cState != "已出库"   ) && cFangxiang == "1")
                            {
                                return new RetModel2() { code = 0, message = "条码不能入库，当前状态为" + cState, data = null };
                            }
                            else if (bARCODEVM[0].cState != "在库" && cFangxiang == "2")
                            {
                                return new RetModel2() { code = 0, message = "条码已出库，当前状态为" + cState, data = null };
                            }
                            else if (bARCODEVM[0].cState.Contains("装箱") && clx.Contains("装箱"))
                            {
                                return new RetModel2() { code = 0, message = "条码已装箱", data = null };
                            }
                            else if (bARCODEVM[0].cState.Contains("拆箱") && clx.Contains("拆箱"))
                            {
                                return new RetModel2() { code = 0, message = "条码已拆箱", data = null };
                            }
                            else if (bARCODEVM[0].cState.Contains("拆托") && clx.Contains("拆托"))
                        {
                            return new RetModel2() { code = 0, message = "条码已拆托", data = null };
                        }
                        //else if (bARCODEVM[0].cState.Contains("装托") && clx.Contains("装托"))
                        //{
                        //    return new RetModel2() { code = 0, message = "条码已装托", data = null };
                        //}
                        else if (clx == "入库装托" && (bARCODEVM[0].cState != "未入库" && bARCODEVM[0].cState != "已出库"))
                            {
                                return new RetModel2() { code = 0, message = "条码当前状态是" + bARCODEVM[0].cState + ",不能装托", data = null };
                            }
                            else if (clx == "库内装托" && (bARCODEVM[0].cState != "在库"))
                            {
                                return new RetModel2() { code = 0, message = "条码当前状态是" + bARCODEVM[0].cState + ",不能装托", data = null };
                            }
                            //出库检查仓库，是不是这个仓库的条码
                            if (cFangxiang == "2" && !string.IsNullOrEmpty(cwhcode) && bARCODEVM[0].cWhCode != cwhcode)
                            {
                                return new RetModel2() { code = 0, message = "条码仓库与当前仓库不一致", data = null };
                            }
                        }



                        //清理条码敏感信息，含数据库字符串
                        foreach (var item in bARCODEVM)
                        {
                            item.clearConstr();
                        }

                        return new RetModel2() { code = 200, message = "ok", data = bARCODEVM };
                    } 
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }

        }

        private RetModel2 AddBarcode(string cbarcode, SqlSugarClient db)
        {
            try
            {
                string[] arr = cbarcode.Split("||");
                if (arr.Length == 6)
                {
                    string cInvCode = arr[0].Trim();
                    string cMocode = arr[1].Trim();
                    string cLot = arr[2].Trim();
                    string cSDCLot = arr[3].Trim();
                    string cLsh = arr[4].Trim();
                    decimal dQty = DbHelper.GetDbdecimal(arr[5]);
                    WMS_BARCODEVM wMS_BARCODE = new WMS_BARCODEVM();
                    wMS_BARCODE.Barcodeno = cbarcode;
                    wMS_BARCODE.cInvCode = cInvCode;
                    wMS_BARCODE.cBatch = cLot;
                    wMS_BARCODE.cPoID = cMocode;
                    wMS_BARCODE.cBDefine1 = cSDCLot;
                    //生产单号拆分出订单号和行号
                    string[] lstmo = cMocode.Split('-');
                    string iMoRow = "";
                    if (lstmo.Length > 0)
                    {
                        cMocode = lstmo[0];
                        iMoRow = lstmo[1];
                    }
                    else
                    {
                        iMoRow = "1";
                    }

                    string sql = string.Format(@"select modid from mom_order a, mom_orderdetail b where a.moid = b.moid and a.mocode='{0}' and b.sortseq = '{1}' ", cMocode, iMoRow);
                    string modid = DbHelper.GetDbString(DbHelper2.ExecuteScalar(sql, CanShu.conStr));
                    if (string.IsNullOrEmpty(modid))
                    {
                        return DBService.ReErrObject("条码错误，生产单号不存在");
                    }
                    else
                    {
                        //barcode.modid = DbHelper.GetDbInt(modid);
                        wMS_BARCODE.iSourceID = DbHelper.GetDbInt(modid);
                    }

                    wMS_BARCODE.iOriQty = dQty;
                    wMS_BARCODE.iQty = dQty;
                    wMS_BARCODE.cState = "未入库";
                    wMS_BARCODE.cType = "CP";
                    wMS_BARCODE.dDate = DateTime.Now;

                    //iGroupType=0,无换算率，1,固定换算率，2,浮动换算率

                    //查询系统内有没有当前批次的生产日期，如果有，使用之前的
                    sql = string.Format(@"select dMdate,dVDate from CurrentStock where cInvCode='{0}' and cBatch='{1}' and isnull(dMdate,'')<>'' ", cInvCode, cBatch);
                    DataTable dt = db.Ado.GetDataTable(sql);

                    if (dt.Rows.Count == 0)
                    {
                        //保质期问题处理
                        InvProperty invProperty = new InventoryVM().GetInvProperty(cInvCode, DateTime.Now.Date.ToString("yyyy-MM-dd"), "");
                        if (invProperty == null)
                        {
                            throw new Exception(string.Format("存货编码{0}不存在", cInvCode));
                        }
                        //有效期管理,根据生产日期或者失效日期推算 
                        if (invProperty.bInvQuality)
                        {
                            wMS_BARCODE.dMDate = DbHelper.GetDbDate(DateTime.Now.Date.ToString("yyyy-MM-dd"));
                            wMS_BARCODE.dVDate = invProperty.dVDate;

                        }
                    }
                    else
                    {
                        //barcode.modid = DbHelper.GetDbInt(modid);
                        wMS_BARCODE.dMDate = DbHelper.GetDbDate(dt.Rows[0]["dMdate"]);
                        wMS_BARCODE.dVDate = DbHelper.GetDbDate(dt.Rows[0]["dVdate"]);
                    }



                    wMS_BARCODE.cUser = "SDC";
                    wMS_BARCODE.cWhCode = "";
                    wMS_BARCODE.cPosCode = "";
                    wMS_BARCODE.BarLevel = 1;
                    wMS_BARCODE.cSource = "MES入库";
                    string cRe = wMS_BARCODE.Add();
                    if (cRe.Contains("Error"))
                    {
                        throw new Exception("生成成品条码出错：" + wMS_BARCODE.Barcodeno + "," + cRe);
                    }
                    return DBService.ReOKObject(wMS_BARCODE);
                }
                else
                {
                    throw new Exception("条码不识别");
                }
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }

        /// <summary>
        /// 读取单据打印的条码
        /// </summary>
        /// <param name="ccode">单据号</param>
        /// <param name="ctype">类型</param> 
        /// <returns></returns>
        public RetModel2 AA_GetArrBarcode(string ccode, string ctype)
        {
            try
            {
                if (string.IsNullOrEmpty(ccode))
                {
                    throw new Exception("单据号为空！");
                }
                //存货过程更改成代码
                if (ctype == "采购到货入库")
                {
                    ctype = "到货单打印";
                }

                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                    //生产日期没有
                    List<WMS_BARCODEVM> bARCODEVM = db.Queryable<WMS_BARCODE>()
                        .InnerJoin<Inventory>((a, i) => a.cInvCode == i.cInvCode)
                        .Where((a, i) => a.cPoID == ccode && (a.cState == "未入库" || a.cState == null || a.cState == ""))
                        .Select((a, i) => new WMS_BARCODEVM
                        {
                            Barcodeno = a.Barcodeno,
                            cInvCode = a.cInvCode,
                            cInvName = i.cInvName,
                            cInvStd = i.cInvStd,
                            cInvAddCode = i.cInvAddCode,
                            cBatch = a.cBatch,
                            iQty = a.iQty,
                            iOriQty = a.iOriQty,
                            cWhCode = a.cWhCode,
                            cPosCode = a.cPosCode,
                            BarLevel = a.BarLevel,
                            iSourceID = a.iSourceID,
                            RKDate = a.RKDate,
                            cInCode = a.cInCode,
                            cInType = a.cInType,
                            cState = a.cState,
                            cInvCodeHB = string.IsNullOrWhiteSpace(a.cBatch) ? "a.cInvCode+" : a.cInvCode + "|" + a.cBatch,
                            cDefPosCode = i.cPosition,
                            cDefWareHouse = i.cDefWareHouse,
                            dMDate = a.dMDate,
                            dVDate = a.dVDate,
                            cFree1 = a.cFree1,
                            cFree2 = a.cFree2,
                            cFree3 = a.cFree3,
                            cFree4 = a.cFree4,
                            cBDefine1 = a.cBDefine1,
                            cBDefine2 = a.cBDefine2,
                            cBDefine3 = a.cBDefine3,
                            cBDefine4 = a.cBDefine4,
                            bSerial = i.bSerial
                        }
                        ).ToList();

                    if (bARCODEVM == null || bARCODEVM.Count == 0)
                    {
                        return new RetModel2() { code = 0, message = "条码不存在", data = null };
                    }




                    //清理条码敏感信息，含数据库字符串
                    foreach (var item in bARCODEVM)
                    {
                        item.clearConstr();
                    }

                    return new RetModel2() { code = 200, message = "ok", data = bARCODEVM };
                }





                //string cProcName = "zdy_szxh_sp_GetBarcode";


                //var barcodeP = new SugarParameter("@cbarcode", cbarcode);
                //var clxP = new SugarParameter("@clx", clx);
                //var cwhcodeP = new SugarParameter("@cwhcode", cwhcode);
                //var resultP = new SugarParameter("@result", null, true);//设置为output
                //var dt = SqlsugarHelper._Instance.Ado.UseStoredProcedure().GetDataTable(cProcName, barcodeP, clxP, cwhcodeP, resultP);



                ////检查条码是否存在
                //string cRe = DbHelper.GetDbString(resultP.Value);
                //if (cRe == "ok")
                //{
                //    ;
                //    List<WMS_BARCODEVM> u8wms001s1 = TableListConverter<WMS_BARCODEVM>.TableToList2(dt);

                //    return DBService.ReOK<WMS_BARCODEVM>(u8wms001s1);
                //}
                //else
                //{
                //    return DBService.ReError<WMS_BARCODEVM>(cRe);
                //}

            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }

        }
        /// <summary>
        ///  生成新的标签
        /// </summary>
        /// <param name="fenPeiList">打印明细</param>
        /// <param name="cType">类型</param>
        /// <param name="username">操作员</param> 
        /// <returns></returns>
        public string GenBarcode(WMS_BARCODE wmsbar, string cType, string cpoid, string username)
        {
            try
            {
                string cDate = DateTime.Now.ToString("yyyy-MM-dd");
                decimal dQty = DbHelper.GetDbdecimal(wmsbar.iQty);
                int iPrintCnt = 1;
                if (string.IsNullOrWhiteSpace(wmsbar.cBatch))
                {
                    wmsbar.cBatch = "";
                }

                SqlParameter[] param = new SqlParameter[]{
                                new SqlParameter("@type",cType),
                                 new SqlParameter("@cpoid",cpoid),
                                 new SqlParameter("@cinvcode",wmsbar.cInvCode),
                                 new SqlParameter("@ddate",cDate),
                                new SqlParameter("@cbatch",wmsbar.cBatch),
                                new SqlParameter("@isouceid","0"),
                                new SqlParameter("@qty" ,dQty),
                                new SqlParameter("@cnt",iPrintCnt),
                                new SqlParameter("@user",username),
                                  new SqlParameter("@dmdate",wmsbar.dMDate),
                                    new SqlParameter("@dvdate",wmsbar.dVDate),
                                      new SqlParameter("@cfree1",wmsbar.cFree1),
                                             new SqlParameter("@cfree2",wmsbar.cFree2),
                                                    new SqlParameter("@cfree3",wmsbar.cFree3),
                                                           new SqlParameter("@cfree4",wmsbar.cFree4),
                                new SqlParameter("@error",SqlDbType.NVarChar,2000)
                  };

                param[15].Direction = ParameterDirection.Output;
                //换wms的连接字符串
                DataSet ds = DbHelper2.Execute("ZDY_SP_SZXH_GenBarcode", param, CommandType.StoredProcedure, CanShu.conStr);


                //检查条码是否存在
                string cre = DbHelper.GetDbString(param[15].Value);
                if (cre == "ok")
                {
                    DataTable dtbar = ds.Tables[0];

                    return DbHelper.GetDbString(dtbar.Rows[0]["barcode"]);
                }
                else
                {
                    return "Error:" + cre;
                }

            }
            catch (Exception ex)
            {
                return "Error:" + ex.Message;
            }
        }

        /// <summary>
        /// 拆箱，按输入的数量进行拆箱
        /// </summary>
        /// <param name="iid"></param>
        /// <returns></returns>
        public RetModel2 ChaiXiangByQty(ScanBarcode scanBarcodes)
        {
            try
            {
                if (scanBarcodes.itemList.Count == 0)
                {
                    return DBService.ReErrObject("没有数据，无法保存");
                }
                string cParentid = System.Guid.NewGuid().ToString();
                List<ZDY_RDRECORDS_ORI> lst = new List<ZDY_RDRECORDS_ORI>();
                //读取原来存货的打印规则
                WMS_BARCODE wmsBar = SqlsugarHelper.Instance.Queryable<WMS_BARCODE>().Where(t => t.Barcodeno == scanBarcodes.cCode).Single();

                string ctype = wmsBar.cType;
                string cpoid = wmsBar.cPoID;
                for (int i = 0; i < scanBarcodes.itemList.Count; i++)
                {

                    ZDY_RDRECORDS_ORI rd = new ZDY_RDRECORDS_ORI();
                    wmsBar.iQty = scanBarcodes.itemList[i].iQuantity;
                    //先生成条码,isourceid 写的是拆箱前的条码
                    string newcode = GenBarcode(wmsBar, ctype, cpoid, scanBarcodes.cUserName);
                    if (newcode.Contains("Error"))
                    {
                        return DBService.ReErrObject(newcode);
                    }
                    else
                    {
                        scanBarcodes.itemList[i].cBarcodeno = newcode;
                        rd.cBarcodeno = newcode;
                    }
                    rd.PARENTID = cParentid;
                    //拆箱前条码
                    rd.cSourceCode = scanBarcodes.cCode;
                    rd.cInvCode = scanBarcodes.itemList[i].cInvCode;
                    rd.cBatch = scanBarcodes.itemList[i].cBatch;
                    rd.iQuantity = scanBarcodes.itemList[i].iQuantity;
                    rd.cType = scanBarcodes.cType;
                    rd.cMaker = scanBarcodes.cUserName;
                    rd.dDate = scanBarcodes.dDate;
                    rd.cWhCode = wmsBar.cWhCode;
                    //rd.cWhName = scanBarcodes.
                    rd.cPosCode = wmsBar.cPosCode;
                    //rd.cPosName = scanBarcodes.cPosName;
                    //rd.cVenCode = scanBarcodes.cVenCode;
                    rd.iSourceId = scanBarcodes.itemList[i].autoid;
                    rd.dMaketime = DateTime.Now;
                    lst.Add(rd);

                    //更新新条码的状态
                    string sql2 = string.Format(@"UPDATE A SET CSTATE='{1}',cIncode='{2}' FROM dbo.WMS_BARCODE a WHERE a.BARCODENO='{0}' ", newcode, wmsBar.cState, scanBarcodes.cCode);
                    DbHelper2.ExecuteNonQuery(sql2, CanShu.conStr);
                }
                //更新原条码状态
                string sql = string.Format(@"UPDATE A SET CSTATE='已拆箱'  FROM dbo.WMS_BARCODE a WHERE a.BARCODENO='{0}' ", scanBarcodes.cCode);
                DbHelper2.ExecuteNonQuery(sql, CanShu.conStr);
                var cnt = SqlsugarHelper.Instance.Insertable(lst) //插入1层 Root->Books
         .ExecuteCommand();
                if (cnt == 0)
                {
                    return DBService.ReErrObject("未保存成功，请重试");
                }

                return DBService.ReOKObject(scanBarcodes.itemList);
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }

        }


        /// <summary>
        /// 装箱
        /// </summary>
        /// <param name="iid"></param>
        /// <returns></returns>
        public RetModel2 ZhuangXiang(ScanBarcodeVM scanBarcodes)
        {
            try
            {
                if (scanBarcodes.itemList.Count == 0)
                {
                    return DBService.ReErrObject("没有数据，无法保存");
                }
                string cParentid = System.Guid.NewGuid().ToString();
                List<ZDY_RDRECORDS_ORI> lst = new List<ZDY_RDRECORDS_ORI>();
                //取第一行的规则，然后更改数量合并
                WMS_BARCODE wmsBar = SqlsugarHelper.Instance.Queryable<WMS_BARCODE>().Where(t => t.Barcodeno == scanBarcodes.itemList[0].cBarcodeno).Single();
                string ctype = wmsBar.cType;
                string cpoid = wmsBar.cPoID;
                wmsBar.iQty = scanBarcodes.itemList.Sum(x => x.iQuantity);
                string newcode = GenBarcode(wmsBar, ctype, cpoid, scanBarcodes.cUserName);


                for (int i = 0; i < scanBarcodes.itemList.Count; i++)
                {
                    ZDY_RDRECORDS_ORI rd = new ZDY_RDRECORDS_ORI();
                    rd.cBarcodeno = scanBarcodes.itemList[i].cBarcodeno;
                    rd.PARENTID = cParentid;
                    rd.cInvCode = scanBarcodes.itemList[i].cInvCode;
                    rd.cBatch = scanBarcodes.itemList[i].cBatch;
                    rd.iQuantity = scanBarcodes.itemList[i].iQuantity;
                    //装箱后条码
                    rd.cSourceCode = newcode;
                    rd.cType = "装箱";
                    rd.cMaker = scanBarcodes.cUserName;
                    rd.dDate = scanBarcodes.dDate;
                    rd.cWhCode = scanBarcodes.cWhCode;
                    //rd.cWhName = scanBarcodes.
                    rd.cPosCode = scanBarcodes.itemList[i].cPosCode;
                    //rd.cPosName = scanBarcodes.cPosName;
                    //rd.cVenCode = scanBarcodes.cVenCode;
                    rd.iSourceId = scanBarcodes.itemList[i].autoid;
                    rd.dMaketime = DateTime.Now;
                    lst.Add(rd);
                    //更新新条码的状态
                    string sql2 = string.Format(@"UPDATE A SET CSTATE='{1}',cIncode='{2}' FROM dbo.WMS_BARCODE a WHERE a.BARCODENO='{0}' ", scanBarcodes.itemList[i].cBarcodeno, "已装箱", newcode);
                    DbHelper2.ExecuteNonQuery(sql2, CanShu.conStr);
                }

                var cnt = SqlsugarHelper.Instance.Insertable(lst) //插入1层 Root->Books
         .ExecuteCommand();
                if (cnt == 0)
                {
                    return DBService.ReErrObject("未保存成功，请重试");
                }

                return DBService.ReOKObject(newcode);
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }

        }

        public RetModel2 ZhuangTuo(ScanBarcodeVM scanBarcodes)
        {
            try
            {
                if (scanBarcodes.itemList.Count == 0)
                {
                    return DBService.ReErrObject("没有数据，无法保存");
                }

                string cParentid = System.Guid.NewGuid().ToString();
                var firstBarcode = scanBarcodes.itemList[0].cBarcodeno;

                WMS_BARCODE wmsBar = SqlsugarHelper.Instance.Queryable<WMS_BARCODE>()
                    .Where(t => t.Barcodeno == firstBarcode)
                    .Single();

                WMS_BARCODE genNoBarcode = new WMS_BARCODE
                {
                    dDate = DateTime.Now.Date,
                    cType = "TM",
                    cInvCode = wmsBar.cInvCode
                };

                string newcode = getNewBarcode(genNoBarcode);
                var lst = scanBarcodes.itemList.Select(x => new WMS_TrayDetail
                {
                    cBarcodeNo = x.cBarcodeno,
                    cTrayNo = newcode
                }).ToList();

                WMS_Tray tray = new WMS_Tray
                {
                    cTrayNo = newcode,
                    dDate = DateTime.Now.Date,
                    cWhCode = scanBarcodes.cWhCode,
                    cPosCode = scanBarcodes.cPosCode,
                    cState = scanBarcodes.cType == "入库装托" ? "未入库" : "在库",
                    cInvCode = wmsBar.cInvCode,
                    iQty = scanBarcodes.itemList.Sum(x => x.iQuantity),
                    dMakeTime = DateTime.Now,
                    cUser = scanBarcodes.cUserName
                };

                // 使用事务确保所有操作原子性
                var result = SqlsugarHelper.Instance.Ado.UseTran(() =>
                {
                    // 插入托盘主表
                    var cnt = SqlsugarHelper.Instance.Insertable(tray).ExecuteCommand();
                    if (cnt == 0) throw new Exception("托盘主表保存失败");

                    // 插入托盘明细
                    cnt = SqlsugarHelper.Instance.Insertable(lst).ExecuteCommand();
                    if (cnt == 0) throw new Exception("托盘明细保存失败");

                    // 批量更新条码状态
                    var barcodeNos = scanBarcodes.itemList.Select(x => x.cBarcodeno).ToList();
                    cnt = SqlsugarHelper.Instance.Updateable<WMS_BARCODE>()
                        .SetColumns(x => x.cState == "已装托"+newcode)
                        .Where(x => barcodeNos.Contains(x.Barcodeno))
                        .ExecuteCommand();

                    if (cnt == 0) throw new Exception("条码状态更新失败");
                });

                if (!result.IsSuccess)
                {
                    return DBService.ReErrObject(result.ErrorMessage);
                }

                return DBService.ReOKObject(newcode);
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }

        public RetModel2 ChaiTuo(string cTrayNo)
        {
            try
            {
                if ( string.IsNullOrEmpty(cTrayNo))
                {
                    return DBService.ReErrObject("托码单号为空");
                }

                 

                // 使用事务确保所有操作原子性
                var result = SqlsugarHelper.Instance.Ado.UseTran(() =>
                { 
                    //更新箱码
                    WMS_Tray tray = SqlsugarHelper.Instance.Queryable<WMS_Tray>()
                        .Where(c => c.cTrayNo == cTrayNo).First();

                   var lst = SqlsugarHelper.Instance.Queryable<WMS_TrayDetail>()
                        .Where(c => c.cTrayNo == cTrayNo)
                        .Select(x => x.cBarcodeNo).ToList();

                
                    var cnt = SqlsugarHelper.Instance.Updateable<WMS_BARCODE>()
                        .SetColumns(x => new WMS_BARCODE
                        {
                            cState= tray.cState,
                            cWhCode= tray.cWhCode,
                            cPosCode= tray.cPosCode
                        })
                        .Where(x => lst.Contains(x.Barcodeno))
                        .ExecuteCommand();
                    
                    if (cnt == 0) throw new Exception("条码状态更新失败");
                    
                    cnt = SqlsugarHelper.Instance.Updateable<WMS_Tray>()
                        .SetColumns(x => x.cState == "已拆托" )
                        .Where(x =>x.cTrayNo==cTrayNo)
                        .ExecuteCommand();
                    if (cnt == 0) throw new Exception("条码状态更新失败");



                });

                if (!result.IsSuccess)
                {
                    return DBService.ReErrObject(result.ErrorMessage);
                }

                return DBService.ReOKObject("完成");
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }
        //        /// <summary>
        //        /// 拆箱
        //        /// </summary>
        //        /// <param name="iid"></param>
        //        /// <returns></returns>
        //        public RetModel<FenPeiList> ChaiXiang(ScanBarcode scanBarcodes)
        //        {
        //            try
        //            {
        //                if (scanBarcodes.fenpeilist.Count == 0)
        //                {
        //                    return DBService.ReError<FenPeiList>("没有数据，无法保存");
        //                }
        //                string cParentid = System.Guid.NewGuid().ToString();
        //                List<ZDY_RDRECORDS_ORI> lst = new List<ZDY_RDRECORDS_ORI>();
        //                //读取原来存货的打印规则
        //                WMS_BARCODE wmsBar = SqlsugarHelper.Instance.Queryable<WMS_BARCODE>().Where(t => t.BARCODENO == scanBarcodes.cCode).Single();

        //                string ctype = wmsBar.CTYPE;
        //                string cpoid = wmsBar.CPOID;
        //                for (int i = 0; i < scanBarcodes.fenpeilist.Count; i++)
        //                {

        //                    ZDY_RDRECORDS_ORI rd = new ZDY_RDRECORDS_ORI();
        //                    //先生成条码,isourceid 写的是拆箱前的条码
        //                    string newcode = GenBarcode(scanBarcodes.fenpeilist[i], ctype, cpoid, scanBarcodes.cUserName);
        //                    if (newcode.Contains("Error"))
        //                    {
        //                        return DBService.ReError<FenPeiList>(newcode);
        //                    }
        //                    else
        //                    {
        //                        scanBarcodes.fenpeilist[i].cBarcodeno = newcode;
        //                        rd.cBarcodeno = newcode;
        //                    }
        //                    rd.PARENTID = cParentid;
        //                    //拆箱前条码
        //                    rd.cSourceCode = scanBarcodes.cCode;
        //                    rd.cInvCode = scanBarcodes.fenpeilist[i].cInvCode;
        //                    rd.cBatch = scanBarcodes.fenpeilist[i].cBatch;
        //                    rd.iQuantity = scanBarcodes.fenpeilist[i].iQuantity;
        //                    rd.cType = scanBarcodes.cType;
        //                    rd.cMaker = scanBarcodes.cUserName;
        //                    rd.dDate = scanBarcodes.dDate;
        //                    rd.cWhCode = scanBarcodes.cWhCode;
        //                    rd.cWhName = scanBarcodes.cWhName;
        //                    rd.cPosCode = scanBarcodes.fenpeilist[i].cPosCode;
        //                    //rd.cPosName = scanBarcodes.cPosName;
        //                    //rd.cVenCode = scanBarcodes.cVenCode;
        //                    rd.iSourceId = scanBarcodes.fenpeilist[i].autoid; 
        //                    rd.dMaketime = DateTime.Now;
        //                    lst.Add(rd);

        //                   //更新新条码的状态
        //                    string sql2 = string.Format(@"UPDATE A SET CSTATE='{1}',cIncode='{2}' FROM dbo.WMS_BARCODE a WHERE a.BARCODENO='{0}' ", newcode, wmsBar.CSTATE, scanBarcodes.cCode);
        //                    DbHelper2.ExecuteNonQuery(sql2, CanShu.conStr);
        //                }
        //                //更新原条码状态
        //                string sql = string.Format(@"UPDATE A SET CSTATE='已拆箱'  FROM dbo.WMS_BARCODE a WHERE a.BARCODENO='{0}' ", scanBarcodes.cCode);
        //                DbHelper2.ExecuteNonQuery(sql, CanShu.conStr);
        //                var cnt = SqlsugarHelper.Instance.Insertable(lst) //插入1层 Root->Books
        //         .ExecuteCommand();
        //                if (cnt == 0)
        //                {
        //                    return DBService.ReError<FenPeiList>("未保存成功，请重试");
        //                }

        //                return DBService.ReOK<FenPeiList>(scanBarcodes.fenpeilist);
        //            }
        //            catch (Exception ex)
        //            {
        //                return DBService.ReError<FenPeiList>(ex.Message);
        //            }

        //        }

        //        /// <summary>
        //        /// 装箱
        //        /// </summary>
        //        /// <param name="iid"></param>
        //        /// <returns></returns>
        //        public RetModelbool ZhuangXiang(ScanBarcode scanBarcodes)
        //        {
        //            try
        //            {
        //                //把明细数据汇总，取数量合计，然后生成条码。这个是明细
        //                if (scanBarcodes.fenpeilist.Count == 0)
        //                {
        //                    return DBService.ReErrorbool("没有数据，无法保存");
        //                }

        //                string cParentid = System.Guid.NewGuid().ToString();
        //                List<ZDY_RDRECORDS_ORI> lst = new List<ZDY_RDRECORDS_ORI>();
        //                for (int i = 0; i < scanBarcodes.fenpeilist.Count; i++)
        //                {
        //                    if (DbHelper.GetDbInt(scanBarcodes.fenpeilist[i].iQuantity) != 0)
        //                    {
        //                        ZDY_RDRECORDS_ORI rd = new ZDY_RDRECORDS_ORI();
        //                        rd.PARENTID = cParentid;
        //                        rd.cSourceCode = scanBarcodes.cCode;
        //                        rd.cInvCode = scanBarcodes.fenpeilist[i].cInvCode;
        //                        rd.cBatch = scanBarcodes.fenpeilist[i].cBatch;
        //                        rd.iQuantity = scanBarcodes.fenpeilist[i].iQuantity;
        //                        rd.cType = scanBarcodes.cType;
        //                        rd.cMaker = scanBarcodes.cUserName;
        //                        rd.dDate = scanBarcodes.dDate;
        //                        rd.cWhCode = scanBarcodes.cWhCode;
        //                        rd.cWhName = scanBarcodes.cWhName;
        //                        rd.cPosCode = scanBarcodes.fenpeilist[i].cPosCode;
        //                        //rd.cPosName = scanBarcodes.cPosName;
        //                        //rd.cVenCode = scanBarcodes.cVenCode;
        //                        rd.iSourceId = scanBarcodes.fenpeilist[i].autoid;
        //                        rd.cBarcodeno = scanBarcodes.fenpeilist[i].cBarcodeno;
        //                        rd.dMaketime = DateTime.Now;

        //                        lst.Add(rd);
        //                    }

        //                }

        //                var cnt = SqlsugarHelper.Instance.Insertable(lst) //插入1层 Root->Books
        //         .ExecuteCommand();
        //                if (cnt == 0)
        //                {
        //                    return DBService.ReErrorbool("未保存成功，请重试");
        //                }

        //                DataTable dtsum = WMSService.OMS_GetBarcodeDetail(CanShu.conStr, cParentid);
        //                if (dtsum.Rows.Count == 0)
        //                {
        //                    throw new Exception("条码无法关联到存货编码");
        //                }
        //                else if (dtsum.Rows.Count >1)
        //                {
        //                    throw new Exception("装箱批次不一样，无法装箱");
        //                }
        //                FenPeiList fenPeiList = new FenPeiList()
        //                {
        //                    cInvCode =DbHelper.GetDbString(dtsum.Rows[0]["cInvCode"]),
        //                    cBatch = DbHelper.GetDbString(dtsum.Rows[0]["cBatch"]),
        //                    iQuantity = DbHelper.GetDbdecimal(dtsum.Rows[0]["QTY"]),
        //                };
        //                //读取原来存货的打印规则
        //                WMS_BARCODE wmsBar = SqlsugarHelper.Instance.Queryable<WMS_BARCODE>().Where(t => t.BARCODENO == scanBarcodes.fenpeilist[0].cBarcodeno).Single();

        //                string ctype = wmsBar.CTYPE;
        //                string cpoid = wmsBar.CPOID;

        //               string newcode =  GenBarcode(fenPeiList, ctype,cpoid,scanBarcodes.cUserName);
        //                   if (newcode.Contains("Error"))
        //                {
        //                    return DBService.ReErrorbool(newcode);
        //                }
        //                 else
        //                {
        //                    //更新zdy_rdrecords_ori
        //                    string sql = string.Format(@" UPDATE A SET cSourceCode='{1}'  FROM  dbo.ZDY_RDRECORDS_ORI A WHERE PARENTID = '{0}' ", cParentid, newcode);
        //                    DbHelper2.ExecuteNonQuery(sql, CanShu.conStr);

        //                    //更新原条码的档案
        //                    sql = string.Format(@"UPDATE A SET CSTATE='已装箱',coutcode='{1}' FROM dbo.WMS_BARCODE a,dbo.ZDY_RDRECORDS_ORI b WHERE a.BARCODENO=b.cBarcodeno
        //AND b.PARENTID = '{0}' ", cParentid, newcode);
        //                    DbHelper2.ExecuteNonQuery(sql, CanShu.conStr);
        //                   //更新仓库和货位
        //                    sql = string.Format(@"UPDATE A SET CWHCODE=b.CWHCODE,CPOSCODE=B.CPOSCODE FROM dbo.WMS_BARCODE a,dbo.WMS_BARCODE b WHERE a.barcodeno='{0}' and b.barcodeno='{1}'",
        //                      newcode, scanBarcodes.fenpeilist[0].cBarcodeno)  ;
        //                    DbHelper2.ExecuteNonQuery(sql, CanShu.conStr);

        //                    return DBService.ReOKbool(newcode);
        //                }

        //            }
        //            catch (Exception ex)
        //            {
        //                return DBService.ReErrorbool(ex.Message);
        //            }

        //        }


        //更改条码的状态,及当前的货位
        //更改条码的状态,及当前的货位
        public void ChangeBarcodestate(string parentid, string cstate)
        {

            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
                if (cstate == "在库")
                {
                    //增加更新入库日期，入库单据号
                    var subQuery = db.Queryable<ZDY_RDRECORDS_ORI>()
         .Where(it => it.PARENTID == parentid)
         .Select(it => new WMS_BARCODE
         {
             Barcodeno = it.cBarcodeno,
             cPosCode = it.cPosCode,
             cWhCode = it.cWhCode,
             cInCode = it.cU8Code,
             cInType = it.cType,
             cState = cstate,
             RKDate = DateTime.Now,
             cUser = it.cMaker,
             iSourceID = it.ID
         }).Distinct();
                    // 将子查询结果转换为列表
                    var subQueryList = subQuery.ToList();

                    // 批量更新 WMS_BARCODE 表
                    foreach (var item in subQueryList)
                    {
                        WMS_BARCODE wMS_BARCODE = GetMutiBarcodeVM(item.Barcodeno,db);
                        //增加日志记录
                        WMS_BARCODE_LOG log = new WMS_BARCODE_LOG();
                        log.cBarcodeno = item.Barcodeno;
                        log.cUserName = item.cUser;
                        log.dMakeTime = DateTime.Now;
                        log.cCode = item.cInCode;
                        log.cSourceId = item.iSourceID.ObjToString();
                        log.cVouchType = item.cInType;
                        log.cRemark = "";
                        log.cWhCode = item.cWhCode;
                        log.cWhCodeBefore = wMS_BARCODE.cWhCode;
                        log.cPosCode = item.cPosCode;
                        log.cPosCodeBefore = wMS_BARCODE.cPosCode;
                        log.iQuantityBefore = wMS_BARCODE.iQty;
                        log.iQuantity = wMS_BARCODE.iQty;
                        log.cStateBefore = wMS_BARCODE.cState;
                        log.cState = cstate;
                        db.Insertable(log).ExecuteCommand();

                         //T 开头的，更新托码
                         if(item.Barcodeno.Substring(0,1)=="T")
                        {
                            db.Updateable<WMS_Tray>()
                           .SetColumns(it => new WMS_Tray
                           {
                               cPosCode = item.cPosCode,
                               cWhCode = item.cWhCode,
                               cInCode = item.cInCode,
                               cInType = item.cInType,
                               cState = item.cState,
                               RKDate = item.RKDate
                           })
                           .Where(it => it.cTrayNo == item.Barcodeno)
                           .ExecuteCommand();
                        }
                        else
                        {
                            db.Updateable<WMS_BARCODE>()
                           .SetColumns(it => new WMS_BARCODE
                           {
                               cPosCode = item.cPosCode,
                               cWhCode = item.cWhCode,
                               cInCode = item.cInCode,
                               cInType = item.cInType,
                               cState = item.cState,
                               RKDate = item.RKDate
                           })
                           .Where(it => it.Barcodeno == item.Barcodeno)
                           .ExecuteCommand();
                        }
                       
                    }


                }
                else if (cstate == "已出库")
                {
                    //增加更新出库日期，出库单据号
                    var subQuery = db.Queryable<ZDY_RDRECORDS_ORI>()
         .Where(it => it.PARENTID == parentid)
         .Select(it => new WMS_BARCODE
         {
             Barcodeno = it.cBarcodeno,
             cPosCode = it.cPosCode,
             cWhCode = it.cWhCode,
             cOutCode = it.cU8Code,
             cOutType = it.cType,
             cState = cstate,
             CKDate = DateTime.Now,
             cUser = it.cMaker,
             iSourceID = it.ID
         }).Distinct();
                    // 将子查询结果转换为列表
                    var subQueryList = subQuery.ToList();
                    // 批量更新 WMS_BARCODE 表
                    foreach (var item in subQueryList)
                    {
                        WMS_BARCODE wMS_BARCODE = GetMutiBarcodeVM(item.Barcodeno, db);
                        //增加日志记录
                        WMS_BARCODE_LOG log = new WMS_BARCODE_LOG();
                        log.cBarcodeno = item.Barcodeno;
                        log.cUserName = item.cUser;
                        log.dMakeTime = DateTime.Now;
                        log.cCode = item.cOutCode;
                        log.cSourceId = item.iSourceID.ObjToString();
                        log.cVouchType = item.cOutType;
                        log.cRemark = "";
                        log.cWhCode = item.cWhCode;
                        log.cWhCodeBefore = wMS_BARCODE.cWhCode;
                        log.cPosCode = item.cPosCode;
                        log.cPosCodeBefore = wMS_BARCODE.cPosCode;
                        log.iQuantityBefore = wMS_BARCODE.iQty;
                        log.iQuantity = wMS_BARCODE.iQty;
                        log.cStateBefore = wMS_BARCODE.cState;
                        log.cState = cstate;
                        db.Insertable(log).ExecuteCommand();

                        if (item.Barcodeno.Substring(0, 1) == "T")
                        {
                            db.Updateable<WMS_Tray>()
                           .SetColumns(it => new WMS_Tray
                           {
                               cPosCode = item.cPosCode,
                               cWhCode = item.cWhCode,
                               cOutCode = item.cOutCode,
                               cOutType = item.cOutType,
                               cState = item.cState,
                               RKDate = item.RKDate
                           })
                           .Where(it => it.cTrayNo == item.Barcodeno)
                           .ExecuteCommand();
                        }
                        else
                        {
                            db.Updateable<WMS_BARCODE>()
                            .SetColumns(it => new WMS_BARCODE
                            {
                                cPosCode = item.cPosCode,
                                cWhCode = item.cWhCode,
                                cOutCode = item.cOutCode,
                                cOutType = item.cOutType,
                                cState = item.cState,
                                RKDate = item.RKDate
                            })
                            .Where(it => it.Barcodeno == item.Barcodeno)
                            .ExecuteCommand();
                        }
                    }

                }
                else if (cstate == "调拨")
                {
                    //取调入仓库
                    var subQuery = db.Queryable<ZDY_RDRECORDS_ORI>()
        .Where(it => it.PARENTID == parentid)
        .Select(it => new WMS_BARCODE
        {
            Barcodeno = it.cBarcodeno,
            cPosCode = it.cPosCode2,
            cWhCode = it.cWhCode2,
            cUser = it.cMaker,
            iSourceID = it.ID,
            cInCode = it.cU8Code
        }).Distinct();

                    // 将子查询结果转换为列表
                    var subQueryList = subQuery.ToList();
                    // 批量更新 WMS_BARCODE 表 
                    foreach (var item in subQueryList)
                    {
                        WMS_BARCODE wMS_BARCODE = GetMutiBarcodeVM(item.Barcodeno, db);
                        //增加日志记录
                        WMS_BARCODE_LOG log = new WMS_BARCODE_LOG();
                        log.cBarcodeno = item.Barcodeno;
                        log.cUserName = item.cUser;
                        log.dMakeTime = DateTime.Now;
                        log.cCode = item.cInCode;
                        log.cSourceId = item.iSourceID.ObjToString();
                        log.cVouchType = "调拨";
                        log.cRemark = "";
                        log.cWhCode = item.cWhCode;
                        log.cWhCodeBefore = wMS_BARCODE.cWhCode;
                        log.cPosCode = item.cPosCode;
                        log.cPosCodeBefore = wMS_BARCODE.cPosCode;
                        log.iQuantityBefore = wMS_BARCODE.iQty;
                        log.iQuantity = wMS_BARCODE.iQty;
                        log.cStateBefore = wMS_BARCODE.cState;
                        log.cState = cstate;
                        db.Insertable(log).ExecuteCommand();

                        if (item.Barcodeno.Substring(0, 1) == "T")
                        {
                            db.Updateable<WMS_Tray>()
                           .SetColumns(it => new WMS_Tray
                           {
                               cPosCode = item.cPosCode,
                               cWhCode = item.cWhCode
                           })
                           .Where(it => it.cTrayNo == item.Barcodeno)
                           .ExecuteCommand();
                        }
                        else
                        {
                            db.Updateable<WMS_BARCODE>()
                            .SetColumns(it => new WMS_BARCODE
                            {
                                cPosCode = item.cPosCode,
                                cWhCode = item.cWhCode
                            })
                            .Where(it => it.Barcodeno == item.Barcodeno)
                            .ExecuteCommand();
                        }
                    }
                }
                else
                {
                    var subQuery = db.Queryable<ZDY_RDRECORDS_ORI>()
        .Where(it => it.PARENTID == parentid)
        .Select(it => new WMS_BARCODE
        {
            Barcodeno = it.cBarcodeno,
            cPosCode = it.cPosCode,
            cWhCode = it.cWhCode,
            cState = cstate,
            cUser = it.cMaker,
            iSourceID = it.ID,
            cInCode = it.cU8Code,
            cInType = it.cType

        }).Distinct();

                    // 将子查询结果转换为列表
                    var subQueryList = subQuery.ToList();
                    // 批量更新 WMS_BARCODE 表
                    // 批量更新 WMS_BARCODE 表
                    foreach (var item in subQueryList)
                    {
                        WMS_BARCODE wMS_BARCODE = GetMutiBarcodeVM(item.Barcodeno, db);
                        //增加日志记录
                        WMS_BARCODE_LOG log = new WMS_BARCODE_LOG();
                        log.cBarcodeno = item.Barcodeno;
                        log.cUserName = item.cUser;
                        log.dMakeTime = DateTime.Now;
                        log.cCode = item.cInCode;
                        log.cSourceId = item.iSourceID.ObjToString();
                        log.cVouchType = item.cInType;
                        log.cRemark = "";
                        log.cWhCode = item.cWhCode;
                        log.cWhCodeBefore = wMS_BARCODE.cWhCode;
                        log.cPosCode = item.cPosCode;
                        log.cPosCodeBefore = wMS_BARCODE.cPosCode;
                        log.iQuantityBefore = wMS_BARCODE.iQty;
                        log.iQuantity = wMS_BARCODE.iQty;
                        log.cStateBefore = wMS_BARCODE.cState;
                        log.cState = cstate;
                        db.Insertable(log).ExecuteCommand();

                        if (item.Barcodeno.Substring(0, 1) == "T")
                        {
                            db.Updateable<WMS_Tray>()
                           .SetColumns(it => new WMS_Tray
                           {
                               cPosCode = item.cPosCode,
                               cWhCode = item.cWhCode,
                               cState = item.cState
                           })
                           .Where(it => it.cTrayNo == item.Barcodeno)
                           .ExecuteCommand();
                        }
                        else
                        {
                            db.Updateable<WMS_BARCODE>()
                            .SetColumns(it => new WMS_BARCODE
                            {
                                cPosCode = item.cPosCode,
                                cWhCode = item.cWhCode,
                                cState = item.cState
                            })
                            .Where(it => it.Barcodeno == item.Barcodeno)
                            .ExecuteCommand();
                        }
                    }
                }

            }
        }


        public WMS_BARCODE GetMutiBarcodeVM(string cBarcodeno, SqlSugarClient db)
        {
            WMS_BARCODE wMS_BARCODE = new WMS_BARCODE();
            if (cBarcodeno.Substring(0,1)=="T")
            {
                ZDY_WMS_V_TrayInfo zDY_WMS_V_TrayInfo = db.Queryable<ZDY_WMS_V_TrayInfo>().Where(x => x.cTrayNo == cBarcodeno) 
                    .First();
                wMS_BARCODE = GetBarcodeVMFromTray(zDY_WMS_V_TrayInfo);
            }
            else
            {
                wMS_BARCODE = db.Queryable<WMS_BARCODE>().Where(x => x.Barcodeno == cBarcodeno).First();
            }
            return  wMS_BARCODE;
        }

        //托码转换成箱码
        public WMS_BARCODE GetBarcodeVMFromTray(ZDY_WMS_V_TrayInfo zDY_WMS_V_TrayInfo)
        {
            WMS_BARCODE wMS_BARCODE = new WMS_BARCODE();
            wMS_BARCODE.Barcodeno = zDY_WMS_V_TrayInfo.cTrayNo;
            wMS_BARCODE.iQty = zDY_WMS_V_TrayInfo.iQty;
            wMS_BARCODE.cInvCode = zDY_WMS_V_TrayInfo.cInvCode;
            wMS_BARCODE.cBatch = zDY_WMS_V_TrayInfo.cBatch;
            wMS_BARCODE.cState = zDY_WMS_V_TrayInfo.cState;
            wMS_BARCODE.cWhCode = zDY_WMS_V_TrayInfo.cWhCode;
            wMS_BARCODE.cPosCode = zDY_WMS_V_TrayInfo.cPosCode;
            wMS_BARCODE.dMDate = zDY_WMS_V_TrayInfo.dMDate;
            wMS_BARCODE.dVDate = zDY_WMS_V_TrayInfo.dVDate;
            wMS_BARCODE.cFree1 = zDY_WMS_V_TrayInfo.cFree1;
            wMS_BARCODE.cFree2 = zDY_WMS_V_TrayInfo.cFree2;
            wMS_BARCODE.cFree3 = zDY_WMS_V_TrayInfo.cFree3;
            wMS_BARCODE.cFree4 = zDY_WMS_V_TrayInfo.cFree4;
            return wMS_BARCODE;

        }

            //更改条码的状态,及当前的货位
            public void ChangeBarcodestate_Qty(string parentid, string cstate)
        {

            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
                if (cstate == "在库")
                {
                    //增加更新入库日期，入库单据号
                    var subQuery = db.Queryable<ZDY_RDRECORDS_ORI>()
         .Where(it => it.PARENTID == parentid)
         .Select(it => new WMS_BARCODE
         {
             Barcodeno = it.cBarcodeno,
             cPosCode = it.cPosCode,
             cWhCode = it.cWhCode,
             cInCode = it.cU8Code,
             cInType = it.cType,
             cState = cstate,
             RKDate = DateTime.Now,
             cUser = it.cMaker,
             iSourceID = it.ID
         }).Distinct();
                    // 将子查询结果转换为列表
                    var subQueryList = subQuery.ToList();

                    // 批量更新 WMS_BARCODE 表
                    foreach (var item in subQueryList)
                    {
                        WMS_BARCODE wMS_BARCODE = GetMutiBarcodeVM(item.Barcodeno, db);
                        //增加日志记录
                        WMS_BARCODE_LOG log = new WMS_BARCODE_LOG();
                        log.cBarcodeno = item.Barcodeno;
                        log.cUserName = item.cUser;
                        log.dMakeTime = DateTime.Now;
                        log.cCode = item.cInCode;
                        log.cSourceId = item.iSourceID.ObjToString();
                        log.cVouchType = item.cInType;
                        log.cRemark = "";
                        log.cWhCode = item.cWhCode;
                        log.cWhCodeBefore = wMS_BARCODE.cWhCode;
                        log.cPosCode = item.cPosCode;
                        log.cPosCodeBefore = wMS_BARCODE.cPosCode;
                        log.iQuantityBefore = wMS_BARCODE.iQty;
                        log.iQuantity = wMS_BARCODE.iQty;
                        log.cStateBefore = wMS_BARCODE.cState;
                        log.cState = cstate;
                        db.Insertable(log).ExecuteCommand();

                        if (item.Barcodeno.Substring(0, 1) == "T")
                        {
                            db.Updateable<WMS_Tray>()
                           .SetColumns(it => new WMS_Tray
                           {
                               cPosCode = item.cPosCode,
                               cWhCode = item.cWhCode,
                               cState = item.cState
                           })
                           .Where(it => it.cTrayNo == item.Barcodeno)
                           .ExecuteCommand();
                        }
                        else
                        {
                            db.Updateable<WMS_BARCODE>()
                            .SetColumns(it => new WMS_BARCODE
                            {
                                cPosCode = item.cPosCode,
                                cWhCode = item.cWhCode,
                                cInCode = item.cInCode,
                                cInType = item.cInType,
                                cState = item.cState,
                                RKDate = item.RKDate
                            })
                            .Where(it => it.Barcodeno == item.Barcodeno)
                            .ExecuteCommand();
                        }
                    }


                }
                else if (cstate == "已出库")
                {
                    //增加更新出库日期，出库单据号
                    var subQuery = db.Queryable<ZDY_RDRECORDS_ORI>()
         .Where(it => it.PARENTID == parentid)
         .Select(it => new WMS_BARCODE
         {
             Barcodeno = it.cBarcodeno,
             cPosCode = it.cPosCode,
             cWhCode = it.cWhCode,
             cOutCode = it.cU8Code,
             cOutType = it.cType,
             cState = cstate,
             CKDate = DateTime.Now,
             cUser = it.cMaker,
             iSourceID = it.ID,
             iQty = (Decimal)it.iQuantity
         }).Distinct();
                    // 将子查询结果转换为列表
                    var subQueryList = subQuery.ToList();
                    // 批量更新 WMS_BARCODE 表
                    foreach (var item in subQueryList)
                    {
                        WMS_BARCODE wMS_BARCODE = GetMutiBarcodeVM(item.Barcodeno, db);
                        //增加日志记录
                        WMS_BARCODE_LOG log = new WMS_BARCODE_LOG();
                        log.cBarcodeno = item.Barcodeno;
                        log.cUserName = item.cUser;
                        log.dMakeTime = DateTime.Now;
                        log.cCode = item.cOutCode;
                        log.cSourceId = item.iSourceID.ObjToString();
                        log.cVouchType = item.cOutType;
                        log.cRemark = "";
                        log.cWhCode = item.cWhCode;
                        log.cWhCodeBefore = wMS_BARCODE.cWhCode;
                        log.cPosCode = item.cPosCode;
                        log.cPosCodeBefore = wMS_BARCODE.cPosCode;
                        log.iQuantityBefore = wMS_BARCODE.iQty;
                        log.iQuantity = wMS_BARCODE.iQty;
                        log.cStateBefore = wMS_BARCODE.cState;
                        log.cState = cstate;
                        db.Insertable(log).ExecuteCommand();

                        //如果扫描数量小于当前条码数量，只更改数量. 改数量的没用托码
                        if (item.iQty < wMS_BARCODE.iQty)
                        {
                            db.Updateable<WMS_BARCODE>()
                           .SetColumns(it => new WMS_BARCODE
                           {
                               cPosCode = item.cPosCode,
                               cWhCode = item.cWhCode,
                               cOutCode = item.cOutCode,
                               cOutType = item.cOutType,
                               iQty = wMS_BARCODE.iQty - item.iQty,
                               RKDate = item.RKDate
                           })
                           .Where(it => it.Barcodeno == item.Barcodeno)
                           .ExecuteCommand();
                        }
                        else
                        {
                            if (item.Barcodeno.Substring(0, 1) == "T")
                            {
                                db.Updateable<WMS_Tray>()
                               .SetColumns(it => new WMS_Tray
                               {
                                   cPosCode = item.cPosCode,
                                   cWhCode = item.cWhCode,
                                   cOutCode = item.cOutCode,
                                   cOutType = item.cOutType,
                                   cState = item.cState,
                                   RKDate = item.RKDate
                               })
                               .Where(it => it.cTrayNo == item.Barcodeno)
                               .ExecuteCommand();
                            }
                            else
                            {
                                    db.Updateable<WMS_BARCODE>()
                                .SetColumns(it => new WMS_BARCODE
                                {
                                    cPosCode = item.cPosCode,
                                    cWhCode = item.cWhCode,
                                    cOutCode = item.cOutCode,
                                    cOutType = item.cOutType,
                                    cState = item.cState,
                                    RKDate = item.RKDate
                                })
                                .Where(it => it.Barcodeno == item.Barcodeno)
                                .ExecuteCommand();
                            }
                        }


                    }

                }
                else if (cstate == "调拨")
                {
                    var subQuery = db.Queryable<ZDY_RDRECORDS_ORI>()
        .Where(it => it.PARENTID == parentid)
        .Select(it => new WMS_BARCODE
        {
            Barcodeno = it.cBarcodeno,
            cPosCode = it.cPosCode,
            cWhCode = it.cWhCode,
            cUser = it.cMaker,
            iSourceID = it.ID,
            cInCode = it.cU8Code
        }).Distinct();

                    // 将子查询结果转换为列表
                    var subQueryList = subQuery.ToList();
                    // 批量更新 WMS_BARCODE 表
                    // 批量更新 WMS_BARCODE 表
                    foreach (var item in subQueryList)
                    {
                        WMS_BARCODE wMS_BARCODE = GetMutiBarcodeVM(item.Barcodeno, db);
                        //增加日志记录
                        WMS_BARCODE_LOG log = new WMS_BARCODE_LOG();
                        log.cBarcodeno = item.Barcodeno;
                        log.cUserName = item.cUser;
                        log.dMakeTime = DateTime.Now;
                        log.cCode = item.cInCode;
                        log.cSourceId = item.iSourceID.ObjToString();
                        log.cVouchType = "调拨";
                        log.cRemark = "";
                        log.cWhCode = item.cWhCode;
                        log.cWhCodeBefore = wMS_BARCODE.cWhCode;
                        log.cPosCode = item.cPosCode;
                        log.cPosCodeBefore = wMS_BARCODE.cPosCode;
                        log.iQuantityBefore = wMS_BARCODE.iQty;
                        log.iQuantity = wMS_BARCODE.iQty;
                        log.cStateBefore = wMS_BARCODE.cState;
                        log.cState = cstate;
                        db.Insertable(log).ExecuteCommand();

                        if (item.Barcodeno.Substring(0, 1) == "T")
                        {
                            db.Updateable<WMS_Tray>()
                           .SetColumns(it => new WMS_Tray
                           {
                               cPosCode = item.cPosCode,
                               cWhCode = item.cWhCode
                           })
                           .Where(it => it.cTrayNo == item.Barcodeno)
                           .ExecuteCommand();
                        }
                        else
                        {
                            db.Updateable<WMS_BARCODE>()
                            .SetColumns(it => new WMS_BARCODE
                            {
                                cPosCode = item.cPosCode,
                                cWhCode = item.cWhCode
                            })
                            .Where(it => it.Barcodeno == item.Barcodeno)
                            .ExecuteCommand();
                        }
                    }
                }
                else
                {
                    var subQuery = db.Queryable<ZDY_RDRECORDS_ORI>()
        .Where(it => it.PARENTID == parentid)
        .Select(it => new WMS_BARCODE
        {
            Barcodeno = it.cBarcodeno,
            cPosCode = it.cPosCode,
            cWhCode = it.cWhCode,
            cState = cstate,
            cUser = it.cMaker,
            iSourceID = it.ID,
            cInCode = it.cU8Code,
            cInType = it.cType

        }).Distinct();

                    // 将子查询结果转换为列表
                    var subQueryList = subQuery.ToList();
                    // 批量更新 WMS_BARCODE 表
                    // 批量更新 WMS_BARCODE 表
                    foreach (var item in subQueryList)
                    {
                        WMS_BARCODE wMS_BARCODE = GetMutiBarcodeVM(item.Barcodeno, db);
                        //增加日志记录
                        WMS_BARCODE_LOG log = new WMS_BARCODE_LOG();
                        log.cBarcodeno = item.Barcodeno;
                        log.cUserName = item.cUser;
                        log.dMakeTime = DateTime.Now;
                        log.cCode = item.cInCode;
                        log.cSourceId = item.iSourceID.ObjToString();
                        log.cVouchType = item.cInType;
                        log.cRemark = "";
                        log.cWhCode = item.cWhCode;
                        log.cWhCodeBefore = wMS_BARCODE.cWhCode;
                        log.cPosCode = item.cPosCode;
                        log.cPosCodeBefore = wMS_BARCODE.cPosCode;
                        log.iQuantityBefore = wMS_BARCODE.iQty;
                        log.iQuantity = wMS_BARCODE.iQty;
                        log.cStateBefore = wMS_BARCODE.cState;
                        log.cState = cstate;
                        db.Insertable(log).ExecuteCommand();

                        if (item.Barcodeno.Substring(0, 1) == "T")
                        {
                            db.Updateable<WMS_Tray>()
                           .SetColumns(it => new WMS_Tray
                           {
                               cPosCode = item.cPosCode,
                               cWhCode = item.cWhCode,
                               cState = item.cState
                           })
                           .Where(it => it.cTrayNo == item.Barcodeno)
                           .ExecuteCommand();
                        }
                        else
                        {
                            db.Updateable<WMS_BARCODE>()
                            .SetColumns(it => new WMS_BARCODE
                            {
                                cPosCode = item.cPosCode,
                                cWhCode = item.cWhCode,
                                cState = item.cState
                            })
                            .Where(it => it.Barcodeno == item.Barcodeno)
                            .ExecuteCommand();
                        }
                    }
                }

            }
        }
        //更改货位调整单的状态,及当前的货位
        public void ChangeBarcodeWhcodePos(string parentid)
        {
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
                //增加更新入库日期，入库单据号
                var subQuery = db.Queryable<ZDY_RDRECORDS_ORI>()
     .Where(it => it.PARENTID == parentid)
     .Select(it => new WMS_BARCODE
     {
         Barcodeno = it.cBarcodeno,
         cPosCode = it.cPosCode2,
         cUser = it.cMaker,
         iSourceID = it.ID,
         cInCode = it.cU8Code,
         cInType = it.cType

     }).Distinct();
                // 将子查询结果转换为列表
                var subQueryList = subQuery.ToList();

                // 批量更新 WMS_BARCODE 表
                // 批量更新 WMS_BARCODE 表
                foreach (var item in subQueryList)
                {
                    WMS_BARCODE wMS_BARCODE = db.Queryable<WMS_BARCODE>().Where(x => x.Barcodeno == item.Barcodeno).First();
                    //增加日志记录
                    WMS_BARCODE_LOG log = new WMS_BARCODE_LOG();
                    log.cBarcodeno = item.Barcodeno;
                    log.cUserName = cUser;
                    log.dMakeTime = DateTime.Now;
                    log.cCode = item.cInCode;
                    log.cSourceId = item.iSourceID.ObjToString();
                    log.cVouchType = item.cInType;
                    log.cRemark = "";
                    log.cWhCode = cWhCode;
                    log.cWhCodeBefore = wMS_BARCODE.cWhCode;
                    log.cPosCode = cPosCode;
                    log.cPosCodeBefore = wMS_BARCODE.cPosCode;
                    log.iQuantityBefore = wMS_BARCODE.iQty;
                    log.iQuantity = wMS_BARCODE.iQty;
                    log.cStateBefore = wMS_BARCODE.cState;
                    log.cState = cState;
                    db.Insertable(log).ExecuteCommand();


                    db.Updateable<WMS_BARCODE>()
                        .SetColumns(it => new WMS_BARCODE
                        {
                            cPosCode = item.cPosCode,
                        })
                        .Where(it => it.Barcodeno == item.Barcodeno)
                        .ExecuteCommand();
                }
            }


        }

        /// <summary>
        /// 删除单据造成的状态更改
        /// </summary>
        /// <param name="parentid">单据parentid</param>
        /// <param name="cVouchType">单据类型</param>
        public RetModel2 ChangeBarcodestate_Del(string cVouchType, string parentid)
        {
            try
            {


                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                    //http调用不能有汉字
                    if (cVouchType == "RD01" || cVouchType == "RD10" || cVouchType == "RD08")
                    {
                        //查询条码明细
                        var subQuery = db.Queryable<ZDY_RDRECORDS_ORI>()
             .Where(it => it.PARENTID == parentid)
             .Select(it => new WMS_BARCODE
             {
                 Barcodeno = it.cBarcodeno,
                 cPosCode = it.cPosCode,
                 cWhCode = it.cWhCode,
                 cInCode = it.cU8Code,
                 cInType = cVouchType,
                 RKDate = DateTime.Now,
                 cUser = it.cMaker,
                 iSourceID = it.ID,
                 iQty = (decimal)it.iQuantity
             }).Distinct();
                        // 将子查询结果转换为列表
                        var subQueryList = subQuery.ToList();
                        string cState = "未入库";
                        // 批量更新 WMS_BARCODE 表
                        foreach (var item in subQueryList)
                        {
                            //负数单据，代表红冲，状态改为在库
                            if (item.iQty < 0)
                            {
                                cState = "在库";
                                item.cInType = cVouchType + "-红冲";
                            }


                            WMS_BARCODE wMS_BARCODE = db.Queryable<WMS_BARCODE>().Where(x => x.Barcodeno == item.Barcodeno).First();


                            //增加日志记录
                            WMS_BARCODE_LOG log = new WMS_BARCODE_LOG();
                            log.cBarcodeno = item.Barcodeno;
                            log.cUserName = item.cUser;
                            log.dMakeTime = DateTime.Now;
                            log.cCode = item.cInCode;
                            log.cSourceId = item.iSourceID.ObjToString();
                            log.cVouchType = item.cInType + "删除";
                            log.cRemark = "";
                            log.cWhCode = item.cWhCode;
                            log.cWhCodeBefore = wMS_BARCODE.cWhCode;
                            log.cPosCode = item.cPosCode;
                            log.cPosCodeBefore = wMS_BARCODE.cPosCode;
                            log.iQuantityBefore = wMS_BARCODE.iQty;
                            log.iQuantity = wMS_BARCODE.iQty;
                            log.cStateBefore = wMS_BARCODE.cState;
                            log.cState = cState;
                            db.Insertable(log).ExecuteCommand();


                            //如果条码当前的状态和新的状态不一致，则更新
                            if (wMS_BARCODE.cState != cState)
                            {
                                if (cState == "在库")
                                {

                                    db.Updateable<WMS_BARCODE>()
                                    .SetColumns(it => new WMS_BARCODE
                                    {
                                        cPosCode = item.cPosCode,
                                        cWhCode = item.cWhCode,
                                        cInCode = item.cInCode,
                                        cInType = item.cInType,
                                        cState = cState,
                                        RKDate = item.RKDate
                                    })
                                    .Where(it => it.Barcodeno == item.Barcodeno)
                                    .ExecuteCommand();
                                }
                                else
                                {
                                    db.Updateable<WMS_BARCODE>()
                                    .SetColumns(it => new WMS_BARCODE
                                    {
                                        cPosCode = "",
                                        cWhCode = "",
                                        cInCode = "",
                                        cInType = "",
                                        cState = cState,
                                        RKDate = item.RKDate
                                    })
                                    .Where(it => it.Barcodeno == item.Barcodeno)
                                    .ExecuteCommand();
                                }
                            }

                        }


                    }
                    else if (cVouchType == "RD11" || cVouchType == "RD32" || cVouchType == "RD09")
                    {
                        //增加更新出库日期，出库单据号
                        var subQuery = db.Queryable<ZDY_RDRECORDS_ORI>()
             .Where(it => it.PARENTID == parentid)
             .Select(it => new WMS_BARCODE
             {
                 Barcodeno = it.cBarcodeno,
                 cPosCode = it.cPosCode,
                 cWhCode = it.cWhCode,
                 cOutCode = it.cU8Code,
                 cOutType = cVouchType,
                 CKDate = DateTime.Now,
                 cUser = it.cMaker,
                 iSourceID = it.ID
             }).Distinct();
                        // 将子查询结果转换为列表
                        var subQueryList = subQuery.ToList();
                        string cState = "在库";
                        // 批量更新 WMS_BARCODE 表
                        foreach (var item in subQueryList)
                        {
                            WMS_BARCODE wMS_BARCODE = db.Queryable<WMS_BARCODE>().Where(x => x.Barcodeno == item.Barcodeno).First();
                            //负数单据，代表红冲，状态改为在库

                            if (item.iQty < 0)
                            {
                                cState = "已出库";
                                item.cOutType = item.cOutType + "-红冲";
                                if (wMS_BARCODE.cState != cState)
                                {
                                    db.Updateable<WMS_BARCODE>()
                                    .SetColumns(it => new WMS_BARCODE
                                    {
                                        cPosCode = "",
                                        cWhCode = "",
                                        cOutCode = item.cOutCode,
                                        cOutType = "红冲删除",
                                        cState = cState,
                                        RKDate = item.RKDate
                                    })
                                    .Where(it => it.Barcodeno == item.Barcodeno)
                                    .ExecuteCommand();

                                }
                            }
                            else if (item.iQty > 0 && item.iQty + wMS_BARCODE.iQty <= wMS_BARCODE.iOriQty)
                            {
                                //出库数量小于当前条码数量，只更改数量
                                cState = wMS_BARCODE.cState;

                                // 更新数量
                                db.Updateable<WMS_BARCODE>()
                               .SetColumns(it => new WMS_BARCODE
                               {
                                   iQty = item.iQty + wMS_BARCODE.iQty
                               })
                               .Where(it => it.Barcodeno == item.Barcodeno)
                               .ExecuteCommand();

                            }
                            else
                            {
                                // 更改状态
                                cState = "在库";
                                if (wMS_BARCODE.cState != cState)
                                {

                                    db.Updateable<WMS_BARCODE>()
                                    .SetColumns(it => new WMS_BARCODE
                                    {
                                        cPosCode = item.cPosCode,
                                        cWhCode = item.cWhCode,
                                        cOutCode = "",
                                        cOutType = "",
                                        cState = cState
                                    })
                                        .Where(it => it.Barcodeno == item.Barcodeno)
                                        .ExecuteCommand();
                                }
                            }

                            //增加日志记录
                            WMS_BARCODE_LOG log = new WMS_BARCODE_LOG();
                            log.cBarcodeno = item.Barcodeno;
                            log.cUserName = item.cUser;
                            log.dMakeTime = DateTime.Now;
                            log.cCode = item.cOutCode;
                            log.cSourceId = item.iSourceID.ObjToString();
                            log.cVouchType = item.cOutType + "-删除";
                            log.cRemark = "";
                            log.cWhCode = item.cWhCode;
                            log.cWhCodeBefore = wMS_BARCODE.cWhCode;
                            log.cPosCode = item.cPosCode;
                            log.cPosCodeBefore = wMS_BARCODE.cPosCode;
                            log.iQuantityBefore = wMS_BARCODE.iQty;
                            log.iQuantity = item.iQty;
                            log.cStateBefore = wMS_BARCODE.cState;
                            log.cState = cState;
                            db.Insertable(log).ExecuteCommand();



                        }

                    }
                    else if (cVouchType == "TV")
                    {
                        var subQuery = db.Queryable<ZDY_RDRECORDS_ORI>()
            .Where(it => it.PARENTID == parentid)
            .Select(it => new WMS_BARCODE
            {
                Barcodeno = it.cBarcodeno,
                cPosCode = it.cPosCode,
                cWhCode = it.cWhCode,
                cUser = it.cMaker,
                iSourceID = it.ID,
                cInCode = it.cU8Code
            }).Distinct();

                        // 将子查询结果转换为列表
                        var subQueryList = subQuery.ToList();
                        // 批量更新 WMS_BARCODE 表
                        // 批量更新 WMS_BARCODE 表
                        foreach (var item in subQueryList)
                        {
                            WMS_BARCODE wMS_BARCODE = db.Queryable<WMS_BARCODE>().Where(x => x.Barcodeno == item.Barcodeno).First();
                            //增加日志记录
                            WMS_BARCODE_LOG log = new WMS_BARCODE_LOG();
                            log.cBarcodeno = item.Barcodeno;
                            log.cUserName = item.cUser;
                            log.dMakeTime = DateTime.Now;
                            log.cCode = item.cInCode;
                            log.cSourceId = item.iSourceID.ObjToString();
                            log.cVouchType = "调拨" + "-删除";
                            log.cRemark = "";
                            log.cWhCode = item.cWhCode;
                            log.cWhCodeBefore = wMS_BARCODE.cWhCode;
                            log.cPosCode = item.cPosCode;
                            log.cPosCodeBefore = wMS_BARCODE.cPosCode;
                            log.iQuantityBefore = wMS_BARCODE.iQty;
                            log.iQuantity = wMS_BARCODE.iQty;
                            log.cStateBefore = wMS_BARCODE.cState;
                            log.cState = "在库";
                            db.Insertable(log).ExecuteCommand();


                            db.Updateable<WMS_BARCODE>()
                                .SetColumns(it => new WMS_BARCODE
                                {
                                    cPosCode = item.cPosCode,
                                    cWhCode = item.cWhCode
                                })
                                .Where(it => it.Barcodeno == item.Barcodeno)
                                .ExecuteCommand();
                        }
                    }


                }
                return DBService.ReOKMsg("删除完成");
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }
        public string Add()
        {
            try
            {
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                    if (db.Queryable<WMS_BARCODE>().Where(x => x.Barcodeno == Barcodeno).Any())
                    {
                        return "Error:已有编码，不能新增";
                    }
                    else
                    {

                        int i = db.Insertable<WMS_BARCODE>(this).ExecuteCommand();
                        //db.Aop.OnLogExecuting = (sql, pars) =>
                        //{

                        //    Console.WriteLine(sql);

                        //};
                        if (i > 0)
                        {
                            return "新增完成";
                        }
                        else
                        {
                            return "Error:新增失败";
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                return "Error" + ex.Message;
            }
        }
        //更新条码状态
        public RetModel2 Update()
        {
            try
            {
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                    WMS_BARCODE wMS_BARCODE = db.Queryable<WMS_BARCODE>().Where(x => x.Barcodeno == Barcodeno).First();
                    if (wMS_BARCODE == null)
                    {
                        throw new Exception("条码不存在");
                    }
                    else
                    {
                        WMS_BARCODE_LOG log = new WMS_BARCODE_LOG();
                        log.cBarcodeno = Barcodeno;
                        log.cUserName = cUser;
                        log.dMakeTime = DateTime.Now;
                        log.cCode = "";
                        log.cSourceId = "";
                        log.cVouchType = "手工调整";
                        log.cRemark = "";
                        log.cWhCode = cWhCode;
                        log.cWhCodeBefore = wMS_BARCODE.cWhCode;
                        log.cPosCode = cPosCode;
                        log.cPosCodeBefore = wMS_BARCODE.cPosCode;
                        log.iQuantityBefore = wMS_BARCODE.iQty;
                        log.iQuantity = wMS_BARCODE.iQty;
                        log.cStateBefore = wMS_BARCODE.cState;
                        log.cState = cState;
                        db.Insertable(log).ExecuteCommand();
                        int i = db.Updateable<WMS_BARCODE>(this).ExecuteCommand();

                        if (i > 0)
                        {
                            return DBService.ReOKObject("更新完成");
                        }
                        else
                        {
                            return DBService.ReErrObject("Error:更新失败");
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }

        //条码日志记录
        public void Log(WMS_BARCODE_LOG log)
        {
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
                db.Insertable<WMS_BARCODE_LOG>(log).ExecuteCommand();
            }
        }


        //生成一个条码号码，没有保存条码数据
        public string getNewBarcode(WMS_BARCODE genBarcodeEntity)
        {
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
                string qianzhui = "";
                int maxValue = 0;
                string lsformat = "";
                var ruleItems = db.Queryable<BASE_BARCODE_RULES>()
                 .Where(r => r.CODE == genBarcodeEntity.cType)
                 .OrderBy(r => r.ITEMTYPE)
                 .ToList();
                BASE_BARCODE_RULE_SEEDS bASE_BARCODE_RULE_SEEDS= new BASE_BARCODE_RULE_SEEDS();
                 

                foreach (var item in ruleItems)
                {
                    if (item.ITEMTYPE == 0) // 固定值
                    {
                        qianzhui += item.FORMATSTR;
                    }
                    else if (item.ITEMTYPE == 1) // 日期
                    {
                        qianzhui += item.FORMATSTR
                            .Replace("yyyy",  genBarcodeEntity.dDate.Year.ToString())
                            .Replace("MM", genBarcodeEntity.dDate.Month.ToString("00"))
                            .Replace("dd", genBarcodeEntity.dDate.Day.ToString("00"))
                            .Replace("yy", genBarcodeEntity.dDate.Year.ToString().Substring(2));
                    }
                    else if (item.ITEMTYPE == 5) // 存货代码
                    {
                        qianzhui += genBarcodeEntity.cInvCode;
                    }
                    //else if (item.ITEMTYPE == 6) // 供应商代码
                    //{
                    //    qianzhui += genBarcodeEntity.;
                    //}
                    else if (item.ITEMTYPE == 7) // 批次
                    {
                        qianzhui += genBarcodeEntity.cBatch;
                    }
                    else if (item.ITEMTYPE == 2) // 流水号
                    {
                        lsformat = item.FORMATSTR;
                        bASE_BARCODE_RULE_SEEDS = db.Queryable<BASE_BARCODE_RULE_SEEDS>()
                            .Where(s => s.CODE == genBarcodeEntity.cType && s.SEED == qianzhui).First();

                        if (bASE_BARCODE_RULE_SEEDS != null)
                        {
                            maxValue = bASE_BARCODE_RULE_SEEDS.SEED_VALUE ?? 0;
                        }
                    }
                }
                var barcode = qianzhui + (maxValue+1).ToString().PadLeft(lsformat.Length, '0');

                if (bASE_BARCODE_RULE_SEEDS != null)
                {
                    bASE_BARCODE_RULE_SEEDS.SEED_VALUE = maxValue + 1;
                    db.Updateable(bASE_BARCODE_RULE_SEEDS).ExecuteCommand();
                }
                else
                {
                    bASE_BARCODE_RULE_SEEDS = new BASE_BARCODE_RULE_SEEDS
                    {
                        CODE = genBarcodeEntity.cType,
                        SEED = qianzhui,
                        SEED_VALUE = maxValue + 1
                    };
                    db.Insertable(bASE_BARCODE_RULE_SEEDS).ExecuteCommand();
                }
               return barcode;
            }
               

            

            



            // 9. 更新流水号
           
        }
    }


    //        //更改调拨条码的状态,及当前的货位
    //        public void ChangeBarcodeWhcodeTV(string parentid)
    //        {
    //            //更细条码的状态
    //            string sql = string.Format(@"UPDATE a SET  CPOSCODE =b.cPosCode2,CWHCODE=B.cWhCode2 FROM dbo.WMS_BARCODE a,dbo.ZDY_RDRECORDS_ORI b WHERE a.BARCODENO=b.cBarcodeno
    //AND b.PARENTID = '{0}' ", parentid);
    //            DbHelper2.ExecuteNonQuery(sql, WMSService.conStr);

    //        }
    
   
}


     

    


     

     

    
     
